package tomcat.handler;

import http.LmyRequest;
import http.LmyResponse;
import servlet.LmyCalServlet;
import servlet.LmyHttpServlet;
import servlet.LmyServlet;
import tomcat.LmyTomcatV3;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * LmyRequestHandler 是一个线程对象
 * 用来处理http请求
 */
public class LmyRequestHandler implements Runnable{

    //定义Socket
    private Socket socket = null;

    public LmyRequestHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        InputStream inputStream = null;
        OutputStream outputStream = null;
        //这里可以对客户端/浏览器进行交互
        try {
            System.out.println(Thread.currentThread().getName() + "正在工作...");
            inputStream = socket.getInputStream();
            //inputStream -> BufferedReader 方便按行读取
//            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
//            System.out.println("当前线程：" + Thread.currentThread().getName());
//            System.out.println("======lmyTomcatV2接收到的数据如下======");
//            String message = null;
//            while ((message = bufferedReader.readLine()) != null) {
//                if (message.length() == 0){
//                    break;
//                }
//                System.out.println(message);
//            }
            //交给LmyRequest封装请求数据
            LmyRequest lmyRequest = new LmyRequest(inputStream);
//            System.out.println("lmyRequest: " + lmyRequest);

            //交给LmyResponse封装OutputStream（真实调用在具体的servlet中）
            outputStream = socket.getOutputStream();
            LmyResponse lmyResponse = new LmyResponse(outputStream);

            //创建LmyServlet对象
//            LmyCalServlet lmyServlet = new LmyCalServlet();
//            lmyServlet.doGet(lmyRequest, lmyResponse);
            String uri = lmyRequest.getUri();
            //判断uri是静态还是动态资源
            //如果是静态资源并读取该资源并返回给浏览器
            //目前并没有启动tomcat，不是一个标准的web工程
            //模拟：把静态资源文件放到target/classes下，方便开发
            if (uri.endsWith(".html")) {
                //得到target/classes根目录
                String path = LmyTomcatV3.class.getResource("/").getPath();
                String staticPath = path + uri.substring(1);
                System.out.println(staticPath);
                File file = new File(staticPath);
                OutputStream outputStream1 = lmyResponse.getOutputStream();
                StringBuilder stringBuilder = new StringBuilder();
                if (!file.exists()) {
                    //没有找到就返回404
                    String resp = LmyResponse.respHeader + "<h1>404 Not Found<h1/>";
                    outputStream1.write(resp.getBytes());
                } else {
                    //读取文件并返回静态资源
                    InputStream inputStream1 = new FileInputStream(staticPath);
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream1, StandardCharsets.UTF_8));
                    String message = null;
                    //加上响应头，提醒浏览器返回html类型静态资源
                    stringBuilder.append(LmyResponse.respHeader);
                    while((message = bufferedReader.readLine()) != null) {
                        stringBuilder.append(message);
                    }
                    outputStream1.write(stringBuilder.toString().getBytes());
                }
                //如果是静态资源，执行完静态资源逻辑关闭资源后就退出方法。
                outputStream1.flush();
                outputStream1.close();
                socket.close();
                return;
            }

            //如果是动态资源就请求servlet
            String servletName = LmyTomcatV3.servletUrlMapping.get(uri);
            System.out.println(servletName);
            LmyHttpServlet lmyHttpServlet = null;
            if (servletName != null) {
                lmyHttpServlet = LmyTomcatV3.servletMapping.get(servletName);
            }

            //调用service()，通过动态绑定机制，调用真正的子类 LmyTomcatV3的对象的service()
            if (!(lmyHttpServlet == null)) {
                lmyHttpServlet.service(lmyRequest, lmyResponse);
            } else {
                //没有这个servlet，返回404提示信息
                String resp = LmyResponse.respHeader + "<h1>404 Not Found<h1/>";
                OutputStream outputStream1 = lmyResponse.getOutputStream();
                outputStream1.write(resp.getBytes());
                outputStream1.flush();
                outputStream1.close();
            }
//            String resp = LmyResponse.respHeader + "<h1>lmyResponse 返回的信息</h1>";
//            OutputStream outputStream1 = lmyResponse.getOutputStream();
//            outputStream1.write(resp.getBytes());
//            outputStream1.flush();
//            outputStream1.close();

//            返回数据给浏览器 -> 封装成 http 响应
//            String respHeader = "HTTP/1.1 200 OK\r\n" +
//                    "Content-Type: text/html;charset=utf-8\r\n\r\n";
//            //再构建http响应体
//            String resp = respHeader + "hi, lmy刘明阳~";
//            System.out.println("======lmyTomcatV2返回的数据如下======");
//            System.out.println(resp);
//            //将resp字符串以字节方式回送
//            outputStream.write(resp.getBytes());
//            outputStream.flush();
//            outputStream.close();
            inputStream.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
